<template>
  <div class="app-container">
    板块二
    <!-- 通知和搜索 -->
    <header v-if="!userId>0" class="myheader" :style="{backgroundImage:`url(${merchant_head})`}">
      <ul>
        <li>
<!--          <van-dropdown-menu>-->
<!--            <van-dropdown-item v-model="select.value" :options="select.option" @open="showPopup" />-->
<!--          </van-dropdown-menu>-->
        </li>
        <li>
          <van-search v-model="search.area" placeholder="所在地区或地名 例如：北京/江苏/宿迁" @search="searchAddress()" left-icon="" />
        </li>
        <li class=" van-icon van-icon-search" @click="searchAddress()">
          <!-- <van-icon name="search" /> -->
        </li>
      </ul>
      <!-- <van-area title="城市" :area-list="areaList" :columns-placeholder="['省', '市', '区']" /> -->
      <van-popup v-model="show" position="top">
        <van-area columns-num="3" :area-list="areaList" @confirm="addConfirm_district" @cancel="hideAreaItem_district" :value="district.code" />
      </van-popup>
    </header>
    <!--广告轮播位-->
    <article v-if="!userId>0" class="adrotation">
      <van-swipe indicator-color="white" class="banner" :autoplay="3000">
        <van-swipe-item v-for="(banner, index) in bannerList" :key="index">
          <img :src="banner.url" @click="redirectTo(banner.link)" />
        </van-swipe-item>
      </van-swipe>
    </article>
    <!--服务类-->
    <section v-if="!userId>0" class="servicetype">
      <div class="mycard">
        <nav>
          <a v-for="(item,index) in servicetype.navList" :key="index" :class="[{'square':currentSort==index},{'active':currentSort==index}]" @click="active(index)" v-text="item"></a>
        </nav>
        <div class="line"></div>
        <ul>
          <li v-for="(item,index) in servicetype.ulList">
            <p>
              <img :src="item.img_url" @click="" />
            </p>
            <p v-text="item.img_context"></p>
          </li>
        </ul>
        <ul>
          <li v-for="(item,index) in servicetype.ulList1">
            <p>
              <img :src="item.img_url" @click="" />
            </p>
            <p v-text="item.img_context"></p>
          </li>
        </ul>
      </div>
      <div class="divider"></div>
    </section>
    <!--工具类-->
    <section v-if="!userId>0" class="toolstype"> </section>
    <!--原料类-->
    <section v-if="!userId>0" class="material"> </section>
    <!--加入喷喷涂涂-->
    <article v-if="!userId>0" class="article" :style="{backgroundImage:`url(${merchant_join})`}">
      <span @click="redirectTo('/store/apply')"></span>
    </article>
    <!--广告位-->
    <section class="mybox">
      <nav>
        <a class="square active" v-text="userId>0?'我管理的门店':'门店推荐'"></a>
      </nav>
      <ul v-for="item in list">
        <li  @click="redirectTo(`/shop/detail?id=${item.id}`)">
          <aside class="left" :style="{backgroundImage:`url(${item.shopLogo})`}"></aside>
          <ul class="right">
            <li v-text="item.shopName"></li>
            <li>
              <a v-if="true" :style="{backgroundColor:'rgba(39,126,239,.8)'}">厂家授权</a>
              <a :style="{backgroundColor:(true?'rgba(255,138,0,.8)':'rgba(207,207,207,.8)')}">个人</a>
            </li>
            <span v-show="item.space!==-1">{{item.space}}km</span>
          </ul>
        </li>
        <div class="divider"></div>
      </ul>
    </section>
  </div>
</template>
<script>
  import {
    Area,
    Card,
    Col,
    Divider,
    DropdownItem,
    DropdownMenu,
    Field,
    Icon,
    Popup,
    Row,
    Search,
    Swipe,
    SwipeItem
  } from 'vant';
  import {
    getMerchantList,
    getWxConfig,
    adList,
  } from '@/api/api';
  import areaList from '@/views/user/module-address-edit/area_all.json';
  import scrollFixed from '@/mixin/scroll-fixed';
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue';
  import wx from 'weixin-js-sdk';
  import icon_blue from '@/assets/images/merchant/icon_blue.png';
  import icon_red from '@/assets/images/merchant/icon_red.png';
  import icon_yellow from '@/assets/images/merchant/icon_yellow.png';
  import merchant_head from '@/assets/images/merchant/merchant_head.jpg';
  import merchant_join from '@/assets/images/merchant/merchant_join1.jpg';

  export default {
    name: '',
    props: ['userId'],
    mixins: [scrollFixed],
    data() {
      return {
        myLocation: {
          lat: 0,
          lng: 0,
        },
        //图片素材 begin
        icon_blue: icon_blue,
        icon_red: icon_red,
        icon_yellow: icon_yellow,
        merchant_head: merchant_head,
        merchant_join: merchant_join,
        //图片素材 end
        search: {
          'area': ''
        },
        select: {
          value: 0,
          option: [{
            text: '地区选择',
            value: 0
          }, ],
        },
        show: false,
        servicetype: {
          navList: ['服务类', '二手供应'],
          ulList: [{
              'img_url': icon_yellow,
              'img_context': '工具维修',
              'img_link': ''
            },
            {
              'img_url': icon_blue,
              'img_context': '二手租赁',
              'img_link': ''
            },
            {
              'img_url': icon_red,
              'img_context': '砂浆喷涂机维护',
              'img_link': ''
            },
          ],
          ulList1: [{
              'img_url': icon_yellow,
              'img_context': '石膏喷涂机维护',
              'img_link': ''
            },
            {
              'img_url': icon_blue,
              'img_context': '真石漆喷涂机维护',
              'img_link': ''
            },
            {
              'img_url': icon_red,
              'img_context': '推喷涂机维护',
              'img_link': ''
            },
          ]
        },
        //默认激活
        currentSort: 0,
        bannerList: [],
        location: {
          lng: null,
          lat: null,
        },
        zoom: 12,
        addressKeyword: '',
        // 新增编辑界面数据
        dataForm: {
          id: null,
          serveName: null,
          logo: null,
          name: null,
          province: null,
          city: null,
          county: null,
          addressDetail: null,
          lat: null,
          lng: null,
          areaCode: null,
          postalCode: null,
          tel: null,
          addTime: null,
          updateTime: null,
          deleted: null,
          title: null
        },
        areaList: areaList,
        address: '全国地区',
        area_code: '',
        province: {
          name: '省',
          code: '100000'
        },
        city: {
          name: '市',
          code: '100000'
        },
        district: {
          name: '区',
          code: '100000'
        },
        activeName: ['1'],
        searchValue: '',
        img: 'https://xintu361.oss-cn-qingdao.aliyuncs.com/ttmall/wgme7a0tguy7h4g1g4sr.png',
        list: [],
        query: {
          shopAddress: undefined
        }
      };
    },
    computed: {},
    watch: {
      // 利用watch方法检测路由变化：
      '$route': function (to, from) {
        console.log("route变化",to,from)
        //this.userId=to.params.userId;
        console.log("用户ID变化："+this.userId)
        this.init()
        console.log("检测列表变化",this.list)
        // 拿到目标参数 to.query.id 去再次请求数据接口
        //this.loadPageData(to.query.id)
      }
    },
    created() {
      console.log("用户ID："+this.userId);
      this.getBannerList()
      this.init();
    },
    mounted() {},
    methods: {
      getBannerList() {
        //商品循环列表
        adList({
          position: 35
        }).then((res) => {
          this.bannerList = res.data.data.list;
        });
      },
      active(index) {
        this.currentSort = index;
      },
      addConfirm_district(e) {
        if (e[0].code == '100000') {
          this.city.name = '区'
        } else {
          this.province.code = e[0].code
          this.province.name = e[0].name
          this.city.code = e[1].code
          this.city.name = e[1].name
          this.district.code = e[2].code
          this.district.name = e[2].name
          this.search.area = this.province.name + this.city.name + this.district.name
        }
        this.show = false
      },
      hideAreaItem_district() {
        this.show = false
      },
      handleName() {
        //console.log(111111);
      },
      init() {
        getWxConfig({
          url: location.href.split('#')[0]
        }).then(res => {
          wx.config({
            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            debug: false,
            // 必填，公众号的唯一标识
            appId: res.data.data.appId,
            // 必填，生成签名的时间戳
            timestamp: res.data.data.timestamp,
            // 必填，生成签名的随机串
            nonceStr: res.data.data.nonceStr,
            // 必填，签名，见附录1
            signature: res.data.data.signature,
            // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            jsApiList: ['checkJsApi', 'openLocation', 'getLocation']
          });
        });
        wx.error(function (res) {
          //alert('出错了：' + res.errMsg); //这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
        });
        let that = this;
        wx.ready(function () {
          wx.checkJsApi({
            jsApiList: ['checkJsApi', 'openLocation', 'getLocation'],
            success: function (res) {
              //alert('成功了：' + res.errMsg);
              console.log("检测微信API成功：", res);
              that.getList();
            }
          });
        });
      },
      //获取经纬度直线距离
      getSpace(lat1, lng1, lat2, lng2) {
        if (!(lat1 && lng1 && lat2 && lng2)) {
          return -1
        } //经纬度不存在返回-1
        let radLat1 = lat1 * Math.PI / 180.0;
        let radLat2 = lat2 * Math.PI / 180.0;
        let a = radLat1 - radLat2;
        let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
        let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        return s // 单位千米
      },
      redirectTo(link) {
        if (link == null || link == '' || link == undefined) {
          return;
        }
        if (link.indexOf('http') != -1) {
          window.location.href = link;
          return;
        }
        this.$router.push({
          path: link
        });
      },
      showPopup() {
        this.show = true

      },
      searchAddress() {
        this.getList();
      },
      //获取渲染数据
      getList() {
        this.list.splice(0,this.list.length);
        this.query.shopAddress = undefined
        this.query.userId=this.userId;
        if (this.search.area) {
          this.query.shopAddress = this.search.area.replace(" ","");
        }
        //更新位置信息不保证成功
        let lat
        let lng
        let that = this
        wx.getLocation({
          type: 'wgs84',
          success(res) {
            console.log('微信位置获取：', res)
            lat = res.latitude
            lng = res.longitude
            that.myLocation.lat = lat;
            that.myLocation.lng = lng;
            getMerchantList(that.query).then(res => {
              that.list.length=0;
              res.data.data.list.forEach(obj => {
                obj['space'] = that.getSpace(that.myLocation.lat, that.myLocation.lng, obj.shopLat, obj.shopLng) || -1
                that.list.push(obj);
              });
            })

          }
        })
      },
    },
    components: {
      [Row.name]: Row,
      [Col.name]: Col,
      [Card.name]: Card,
      BaiduMap,
      [Field.name]: Field,
      [Area.name]: Area,
      [Icon.name]: Icon,
      [Swipe.name]: Swipe,
      [SwipeItem.name]: SwipeItem,
      [Divider.name]: Divider,
      [Search.name]: Search,
      [DropdownMenu.name]: DropdownMenu,
      [DropdownItem.name]: DropdownItem,
      [Popup.name]: Popup,
    },
  };

</script>
<style lang="scss" scoped>
  /**方形图标 */
  .square::before {
    color: #1B91FE;
    content: '▍';
  }

  .active {
    color: rgb(0, 0, 0);
    font-weight: bolder;
  }

  /**分割快 */
  .divider {
    display: block;
    width: 100%;
    height: 10px;
    min-width: 50px;
    margin: 0 auto;
    background-color: rgba(242, 242, 242, 1);
  }

  /**分割线 */
  .line {
    width: 100%;
    height: 1px;
    background-color: rgba(125, 125, 125, .2);
    transform: scale(1, 0.5);
  }

  .myheader {
    background-size: 100% 100%;
    height: 185px;
    background-repeat: no-repeat;
    position: relative;

    >ul {
      height: 40px;
      padding: 0 16px;
      display: flex;
      transform: translateY(50%);

      /*li:nth-of-type(1) {*/
      /*  width: 100px;*/

      /*  .van-dropdown-menu {*/
      /*    box-sizing: border-box;*/
      /*    border-top-left-radius: 20px;*/
      /*    height: 100%;*/
      /*    background-color: transparent;*/
      /*    border-bottom-left-radius: 20px;*/
      /*    border: 1px solid #4570CE;*/

      /*    /deep/.van-dropdown-menu__title {*/
      /*      color: rgb(255, 255, 255) !important;*/
      /*    }*/
      /*  }*/
      /*}*/

      li:nth-of-type(2) {
        flex: 1;

        .van-search {
          padding: 0 12px;
          height: 100%;
          background-color: transparent !important;
          padding: 0 0px;

          .van-search__content {
            align-items: center;
            height: 100%;
            flex: 1;
            padding-left: 8px;
            background-color: transparent;
            border: 1px solid #4570CE;
            box-sizing: border-box;
            //border-left-width: 0px;
          }

          /deep/ .van-field__control {
            color: rgb(255, 255, 255) !important;
          }

        }
      }

      li:nth-of-type(3) {
        border: 1px solid #4570CE;
        width: 40px;
        height: 40px;
        border-bottom-right-radius: 20px;
        border-top-right-radius: 20px;
        box-sizing: border-box;
        border-left-width: 0px;
        align-items: center;
        justify-content: center;
        display: flex;
        color: white;
        cursor: pointer;
        font-size: 16px;
      }
    }

    .van-popup {
      margin-top: 60px;
    }
  }

  .adrotation {
    height: 160px;
    padding: 0 16px;
    transform: translateY(-70%);

    .van-swipe {
      height: 100%;
      width: 100%;
      border-radius: 10px;
    }

    .van-swipe-item img {
      width: 100%;
      height: 100%;

    }
  }

  .servicetype {
    margin-top: -100px;
    background-color: rgb(255, 255, 255);

    li,
    li a {
      cursor: pointer;
    }

    .mycard {

      ul,
      nav {
        padding: 0 16px;
      }

      nav {
        display: flex;
        height: 30px;
        align-items: center;

        a {
          display: block;
          margin-right: 20px;
          color: #5B5B5B;
        }

      }

      ul {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        align-content: center;

        li {
          width: 5rem;
          height: 5rem;

          p {
            margin: 0 0;
            padding: 0 0;
            display: flex;
            align-items: center;
            justify-content: center;
                font-size: 11px;
          }

          p:nth-of-type(1) {
            height: 4rem;

            img {
              width: 4rem;
              height: 4rem;
              transform: scale(.85);
            }
          }

          p:nth-of-type(2) {
            overflow: hidden;
            white-space: nowrap;
            height: 1rem;
          }
        }
      }
    }
  }

  .article {
    position: relative;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    height: 100px;

    span {
      transform: scale(.7);
      border-radius: 50%;
      width: 100Px;
      height: 100px;
      position: absolute;
      display: block;
      right: 0;
      z-index: 1;
    }
  }

  .mybox {
    background-color: white;

    nav {
      display: flex;
      height: 30px;
      align-items: center;
      padding: 0 16px;

      a {
        display: block;
        margin-right: 20px;
        color: #5B5B5B;
        transform: scale(1.1);
      }
    }

    ul {
      >li {
        height: 100px;
        width: 100%;
        padding: 0 16px;
        margin: 16px 0;
        display: flex;

        .left {
          background-color: #1E7BF4;
          background-size: 100% 100%;
          width: 100px;
          height: 100px;
          background-repeat: no-repeat;
          box-sizing: border-box;
          box-shadow: 2.5px 2.5px 5px;
        }

        .right {
          flex: 1;
          display: flex;
          flex-direction: column;
          position: relative;

          >li {
            flex: 1;
            display: flex;
            align-items: center;
            padding-right: 32px;
            margin: 0
          }

          >li:nth-of-type(1) {
            font-size: 15px;
            font-weight: bold;
          }

          >li:nth-of-type(2) {
            a {
              display: block;
              height: 20px;
              line-height: 20px;
              color: white;
              padding: 0 6px;
              margin-right: 16px;
            }
          }

          span {
            right: 0;
            top: 50%;
            position: absolute;
            display: block;
            height: 20px;
            line-height: 20px;
            transform: translateY(-10px);
            color: #5B5B5B;
          }
        }
      }

      div.divider {
        height: 8px;
      }
    }
  }

</style>
